<?php

namespace App\Model;

use App\Jobs\CheckOrder;
use App\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class Order extends BaseModel
{
    use HasFactory;

    public $table = 'order';

    public $guarded = [];

    public $casts = [
        'updated_at' => 'date:Y-m-d H:i:s',
        'created_at' => 'date:Y-m-d H:i:s',
        'bill_id' => 'json'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function business()
    {
        return $this->belongsTo(Business::class);
    }

    public function house()
    {
        return $this->belongsTo(House::class)->withTrashed();
    }

    public function device()
    {
        return $this->belongsTo(Device::class);
    }

    public function refund(){
        return $this->hasMany(UserRefund::class,'order_id','id');
    }

    public function setCache(){
        $key = 'FAIL_OERER'.$this->order_no;
//        $mac = $this->device->mac;
//        if($this->device->is_master == 0){
//            $mac = $this->device->m_mac;
//        }
//        $count = Device::query()->where('m_mac',$mac)->count();
        $count = 4;
        Redis::setex($key,($count+1)*60,1);
        dispatch(new CheckOrder($this->order_no))->delay(60*$count-10);
    }


    public function checkCache(){
        $key = 'FAIL_OERER'.$this->order_no;
        $ttl = 0;
        if(Redis::exists($key)){
            $ttl = Redis::ttl($key);
        }
        return $ttl;
    }


    public function checkDraw()
    {
        if($this->business->is_draw == 0 || $this->device->type == 2){
            return ;
        }
        $cacheKey ='DRAW_ORDER'. $this->business_id;
        if(Redis::exists($cacheKey)){
            $fee = Redis::get($cacheKey);
        }else{
            $fee = 0 ;
            Redis::set($cacheKey,0);
        }
        if($fee >= $this->business->draw_max){
            $checkTime = Order::where('user_id', $this->user_id)
                ->where('device_id',$this->device_id)
                ->select('id')
                ->limit(2)
                ->offset(1)
                ->exists();
            if($checkTime && $this->pay_amt <= $this->business->draw_fee){
                $this->is_draw = 1;
                $this->save();
                Redis::del($cacheKey);
            }else{
                Redis::incrByFloat($cacheKey,(float)$this->pay_amt);
            }
        }else{
            Redis::incrByFloat($cacheKey,(float)$this->pay_amt);
        }
    }
}
